<?php

namespace App\Http\Controllers;

// 用户模型
use App\Models\Business\Business as BusinessModel;
use App\Models\Product\Product as ProductModel;
use App\Models\Product\Cart as CartModel;
use App\Models\Business\Address as AddressModel;
use App\Models\Region as RegionModel;
use App\Models\Product\Order as OrderModel;
use App\Models\Product\OrderProduct as OrderProductModel;
use App\Models\Business\Record as RecordModel;
use App\Models\Expressquery as ExpressqueryModel;
use App\Models\Config as ConfigModel;
use App\Models\Depot\Back as BackModel;
use App\Models\Depot\BackProduct as BackProductModel;

// 引入Validator 门面 
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;



class Order extends Controller
{
    // 下单
    public function add()
    {
        // 获取参数
        $params = request()->all(); //获取所有参数
        $addressid = $params['addressid'] ?? 0; //收货地址id
        $cartids = $params['cartids'] ?? 0; //购物车id
        $busid = $params['busid'] ?? 0; //用户id

        // 判断查询购物车商品，从购物车或者从商品详情立即购买获取
        if ($cartids != 0) {
            $cartids = explode(',', $cartids); // exxplode(',', $cartids); 获取购物车id
        }

        // 用户信息
        $businessinfo = BusinessModel::find($busid);

        // 判断用户是否存在
        if (!$businessinfo) {
            return error('用户不存在');
        }

        // 收货地址
        $addressinfo = AddressModel::find($addressid);

        // 判断收货地址是否存在
        if (!$addressinfo) {
            return error('收货地址不存在');
        }

        // 购物车
        $cartlist = CartModel::with('product')->whereIn('id', $cartids)->get();

        // 判断购物车是否存在
        if (!$cartlist) {
            return error('购物车商品不存在');
        }

        // 余额
        $money = bcsub($businessinfo['money'], $params['amount'], 2); // bcsub() 减法 参数： 1 减数 2 被减数 3 保留小数位数

        // 判断余额是否充足
        if ($money < 0) {
            return error('余额不足，请去充值');
        }

        // 开启事务
        DB::beginTransaction();

        try {

            $code = build_code('SP'); // 生成订单编号

            $OrderData = [
                'code' => $code, // 订单编号
                'busid' => $busid, // 用户id
                'amount' => $params['amount'], // 订单金额
                'remark' => $params['remark'], // 订单备注
                'status' => '1', // 订单状态
                'consignee' => $addressinfo['consignee'], // 收货人
                'province' => $addressinfo['province'], // 省
                'city' => $addressinfo['city'], // 市
                'district' => $addressinfo['district'], // 区
                'address' => $addressinfo['address'], // 详细地址
                'mobile' => $addressinfo['mobile'], // 手机
            ];

            // 加校验器
            $OdreStatus = OrderModel::create($OrderData); //crreate() 添加数据

            // 判断订单是否添加成功
            if ($OdreStatus === false) {
                return error('操作失败');
            }


            // 订单产品表
            $OdrerProdcutData = [];

            // 产品表
            $ProductData = [];

            foreach ($cartlist as $item) {
                // 库存
                $stock = bcsub($item['product']['stock'], $item['nums']); // bcsub() 减法 参数： 1 减数 2 被减数 3 保留小数位数

                // 判断库存是否充足
                if ($stock < 0) {
                    return error($item['product']['name'] . '库存不足');
                }

                // 组装产品表
                $ProductData[] = [
                    'id' => $item['proid'],
                    'stock' => $stock
                ];

                // 组装订单产品表
                $OdrerProdcutData[] = [
                    'orderid' => $OdreStatus->id,
                    'proid' => $item['proid'],
                    'pronum' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            // 加校验器  循环校验
            $OdrerProdcutStatus = OrderProductModel::insert($OdrerProdcutData); //insert() 添加数据 批量添加

            if (!$OdrerProdcutStatus) {
                return error('操作失败');
            }

            $BusinessStatus = BusinessModel::where('id', $busid)->update(['money' => $money]); //update() 更新数据 更新余额

            // 判断余额是否更新成功
            if ($BusinessStatus === false) {
                return error('操作失败');
            }

            // 记录
            $RecordData = [
                'total' => $params['amount'], // 金额
                'content' => '商城订单号：' . $code . '---消费的金额' . $params['amount'] . '元', // 内容0
                'busid' => $busid,
                'state' => '2'
            ];

            $RecordStatus = RecordModel::create($RecordData); //create() 添加数据

            // 判断记录是否添加成功
            if (!$RecordStatus) {
                return error('操作失败');
            }

            $CartStatus = CartModel::destroy($cartids); // destroy() 删除数据

            // 判断购物车是否删除成功
            if (!$CartStatus) {
                return error('操作失败');
            }

            // 商品表更新库存
            $ProductStatus = $this->updateBatch('pre_product', $ProductData);

            // 判断商品表是否更新成功
            if ($ProductStatus === false) {
                return error('操作失败');
            }

            DB::commit();
            return success('下单成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return error('下单失败');
        }
    }

    // 列表
    public function index()
    {
        $busid = request('busid', 0);
        $status = request('status', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $dp = OrderModel::query();

        if (!empty($status) ||  $status == '0') {
            if ($status == '-1') {
                $dp->whereIn('status', ['-1', '-2', '-3']);
            } else if ($status == '-4') {
                $dp->whereIn('status', ['-4', '-5']);
            } else {
                $dp->whereIn('status', [$status]);
            }
        }

        $orderlist = $dp->where('busid', $busid)->orderBy('createtime', 'desc')->get();

        foreach ($orderlist as $item) {

            $info = OrderProductModel::with('product')->where('orderid', $item['id'])->first();

            $item['info'] = $info;
        }


        return success('', $orderlist);
    }

    // 详情
    public function info()
    {

        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $orderproid = request('orderproid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $where = [];
        $where['orderid'] = $orderid;
        if ($orderproid > 0) {
            $where['id'] = $orderproid;
        }

        $info = OrderProductModel::with('product')->where($where)->get();

        $orderinfo['info'] = $info;

        // 商家地址
        $contacts = ConfigModel::where('name', 'contacts')->value('value');
        $telephone = ConfigModel::where('name', 'telephone')->value('value');
        $address = ConfigModel::where('name', 'address')->value('value');

        $orderinfo['contacts'] = $contacts;
        $orderinfo['telephone'] = $telephone;
        $orderinfo['address'] = $address;

        return success('', $orderinfo);
    }

    // 确认收货
    public function receipt()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $result = OrderModel::where('id', $orderid)->update(['status' => '3']);

        if ($result === false) {
            return error('操作失败');
        } else {
            return success('操作成功');
        }
    }

    // 物流详情
    public function express()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        if ($orderinfo['expresscode']) {
            $lists = query_express($orderinfo['expresscode']);
            return success('', $lists);
            // 获取缓存物流
            if (cache()->get($orderinfo['expresscode'])) {
                $data = cache()->get($orderinfo['expresscode']);
                return success('', $data);
            } else {
                $res = query_express($orderinfo['expresscode']);
                if ($res['result'] == false) {
                    return error($res['msg']);
                }
                // 缓存物流信息
                cache()->put($orderinfo['expresscode'], $res['data']);
                return success('', $res['data']);
            }
        }
    }

    // 评价
    public function rate(Request $request)
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $orderproid = request('orderproid', 0);
        $rate = request('rate', '');
        $comment = request('comment', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $orderproductlist = OrderProductModel::where('orderid', $orderid)->get();

        if (!$orderproductlist) {
            return error('订单商品不存在');
        }

        // 判断是否是订单最后一个商品评价
        $status = true;

        foreach ($orderproductlist as $item) {
            if (!$item['rate'] && $item['id'] != $orderproid) {
                $status = false;
            }
        }

        if ($status) {
            DB::beginTransaction();

            try {

                // 更新订单表，把状态从待评价改成已完结
                $OrderStatus = OrderModel::where('id', $orderid)->update(['status' => '4']);
                if ($OrderStatus === false) {
                    return error('操作失败');
                }

                $data = [
                    'rate' => $rate,
                    'comment' => $comment,
                    'busid' => $busid
                ];

                // 判断文件是否上传
                if (isset($_FILES[$orderproid]) && count($_FILES[$orderproid]['size']) > 0) {
                    $res = uploads_list($orderproid, $request);
                    if ($res['code'] == 0) {
                        return error($res['msg']);
                    }
                    $data['proimg'] = implode(',', $res['data']);
                }

                $OrderProductStatus = OrderProductModel::where('id', $orderproid)->update($data);

                if ($OrderProductStatus === false) {
                    return error('操作失败');
                }

                DB::commit();
                return success('评价成功');
            } catch (\Exception $e) {
                DB::rollBack();
                // var_dump($e->getMessage());
                return error('评价失败');
            }
        }
        // 多个商品评价
        else {
            $data = [
                'rate' => $rate,
                'comment' => $comment,
                'busid' => $busid
            ];

            // 判断文件是否上传
            if (isset($_FILES[$orderproid]) && count($_FILES[$orderproid]['size']) > 0) {
                $res = uploads_list($orderproid, $request);
                if ($res['code'] == 0) {
                    return error($res['msg']);
                }
                $data['proimg'] = implode(',', $res['data']);
            }

            $result = OrderProductModel::where('id', $orderproid)->update($data);

            if ($result === false) {
                return error('评价失败');
            } else {
                return success('评价成功');
            }
        }
    }

    // 申请退货
    public function refund()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        $status = request('status', '');
        $refundreason = request('refundreason', '');

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        $orderinfo = OrderModel::find($orderid);

        if (!$orderinfo) {
            return error('订单不存在');
        }

        $data = [
            'status' => $status,
            'refundreason' => $refundreason
        ];

        $result = OrderModel::where('id', $orderid)->update($data);

        if ($result === false) {
            return error('申请失败');
        } else {
            return success('申请功，待商家审核');
        }
    }

    // 获取收货地址和物流信息
    public function rejected()
    {
        $busid = request('busid', 0);

        $businessinfo = BusinessModel::find($busid);

        if (!$businessinfo) {
            return error('用户不存在');
        }

        // 获取物流列表
        $expresslist = ExpressqueryModel::select('id as value', 'name as text')->get();

        // 地址
        $addresslist = AddressModel::where('busid', $busid)->get();

        $address = [];

        foreach ($addresslist as $item) {
            $address[] = [
                'text' => $item['consignee'] . '-' . $item['mobile'] . '-' . $item['region_text'],
                'value' => $item['id']
            ];
        }

        $data = [
            'expresslist' => $expresslist,
            'address' => $address
        ];

        return success('', $data);
    }

     // 退货商品
     public function refundgoods()
     {
         $busid = request('busid', 0);
         $orderid = request('orderid', 0);
         $addressid = request('addressid', 0);
         $expressid = request('expressid', 0);
         $expresscode = request('expresscode', 0);
 
         $businessinfo = BusinessModel::find($busid);
 
         if (!$businessinfo) {
             return error('用户不存在');
         }
 
         $orderinfo = OrderModel::find($orderid);
 
         if (!$orderinfo) {
             return error('订单不存在');
         }
 
         $addressinfo = AddressModel::find($addressid);
 
         if (!$addressinfo) {
             return error('地址不存在');
         }
 
         $expressinfo = ExpressqueryModel::find($expressid);
         if (!$expressinfo) {
             return error('物流公司不存在');
         }
 
         $orderproductlist = OrderProductModel::where('orderid', $orderid)->get();
 
         if (!$orderproductlist) {
             return error('退货商品不存在');
         }
 
         DB::beginTransaction();
 
         try {
 
             $code = build_code('BP');
 
             $OrderData = [
                 'code' => $code,
                 'ordercode' => $orderinfo['code'],
                 'busid' => $busid,
                 'contact' => $addressinfo['consignee'],
                 'phone' => $addressinfo['mobile'],
                 'address' => $addressinfo['address'],
                 'province' => $addressinfo['province'],
                 'city' => $addressinfo['city'],
                 'district' => $addressinfo['district'],
                 'amount' => $orderinfo['amount'],
                 'status' => '1',
                 'expressid' => $expressid,
                 'expresscode' => $expresscode
             ];
 
             // 加校验器
             $BackStatus = BackModel::create($OrderData);
 
             if ($BackStatus === false) {
                 return error('操作失败');
             }
 
             // 退货产品表
             $BackProdcutData = [];
 
             foreach($orderproductlist as $item)
             {
                 $BackProdcutData[] = [
                     'backid' => $BackStatus->id,
                     'proid' => $item['proid'],
                     'nums' => $item['pronum'],
                     'price' => $item['price'],
                     'total' => $item['total']
                 ];
             }
 
             // 循环校验
             $BackProdcutStatus = BackProductModel::insert($BackProdcutData);
 
             if ($BackProdcutStatus === false) {
                 return error('操作失败');
             }
             DB::commit();
             return success('操作成功');
         } catch (\Exception $e) {
             DB::rollBack();
             return error('操作失败');
         }
     }
 
     // 退货详情
     public function back()
     {
         $busid = request('busid', 0);
         $orderid = request('orderid', 0);
 
         $businessinfo = BusinessModel::find($busid);
 
         if (!$businessinfo) {
             return error('用户不存在');
         }
 
         $orderinfo = OrderModel::find($orderid);
 
         if (!$orderinfo) {
             return error('订单不存在');
         }
 
         $backinfo = BackModel::where('ordercode', $orderinfo['code'])->first();
 
         $data = [
             'back' => $backinfo,
             'expresslist' => []
         ];
 
         if (isset($backinfo['expresscode']) &&  $backinfo['expresscode']) {
             // $lists = '[{"time":"2018-03-09 11:59:26","status":"【石家庄市】 快件已在 【长安三部】 签收,签收人: 本人, 感谢使用中通快递,期待再次为您服务!"},{"time":"2018-03-09 09:03:10","status":"【石家庄市】快件已到达【长安三部】（0311-85344265）,业务员 容晓光（15908220064）正在第1次派件"},{"time":"2018-03-08 23:43:44","status":"【石家庄市】 快件离开 【石家庄】 发往 【长安三部】"},{"time":"2018-03-08 21:00:44","status":"【石家庄市】 快件到达 【石家庄】"},{"time":"2018-03-07 01:38:45","status":"【广州市】 快件离开 【广州中心】 发往 【石家庄】"},{"time":"2018-03-07 01:36:53","status":"【广州市】 快件到达 【广州中心】"},{"time":"2018-03-07 00:40:57","status":"【广州市】 快件离开 【广州花都】 发往 【石家庄中转】"},{"time":"2018-03-07 00:01:55","status":"【广州市】 【广州花都】（020-37738523） 的 马溪 （18998345739） 已揽收"}]';
             // 获取缓存物流
             if (cache()->get($backinfo['expresscode'])) {
                 $data['expresslist'] = cache()->get($backinfo['expresscode']);
                 return success('', $data);
             } else {
                 $res = query_express($backinfo['expresscode']);
                 if ($res['result'] == false) {
                     return error($res['msg']);
                 }
                 // 缓存物流信息
                 cache()->put($backinfo['expresscode'], $res['data']);
                 $data['expresslist'] = $res['data'];
             }
         }
 
         return success('', $data);
     }

    //查询评价
    public function comment()
    {
        $proid = request('proid', 0);
        $busid = request('busid', 0);

        $where = [
            'proid' => $proid,
            'busid' => $busid
        ];

        $orderproductinfo = OrderProductModel::where($where)->get();


        return success('', $orderproductinfo);
    }

    // 批量更新多条数据方法
    public function updateBatch($tableName = "", $multipleData = array())
    {
        if ($tableName && !empty($multipleData)) {

            // column or fields to update  
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id  
            unset($updateColumn[0]);
            $whereIn = "";

            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .=  $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" .  rtrim($whereIn, ', ') . ")";

            // Update    
            return DB::update(DB::raw($q));
        } else {
            return false;
        }
    }

    //创建订单
    public function sgladd()
    {
        $busid = request('busid', 0);
        $proid = request('proid', 0);
        $remark = request('remark', '');
        $addressid = request('addressid', 0);
        $productinfo = ProductModel::find($proid);
        if (!$productinfo) {
            return error('商品不存在');
        }
        if ($productinfo['stock'] < 0) {
            return error('库存不足');
        }
        $addressinfo = AddressModel::find($addressid);
        if (!$addressinfo) {
            return error('地址不存在');
        }
        // var_dump($addressinfo);
        DB::beginTransaction();
        try {
            $code = build_code("SP");
            $OrderData = [
                'code' => $code,
                'busid' => $busid,
                'amount' => $productinfo['price'],
                'remark' => $remark,
                'status' => '0',
                'consignee' => $addressinfo['consignee'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'address' => $addressinfo['address'],
                'mobile' => $addressinfo['mobile'],
            ];
            //订单表

            $OdreStatus = OrderModel::create($OrderData);
            if ($OdreStatus === false) {
                return error('操作失败');
            }
            //订单商品表
            $data2 = [
                'orderid' => $OdreStatus->id,
                'proid' => $proid,
                'pronum' => '1',
                'price' => $productinfo['price'],
                'total' => $productinfo['price']
            ];
            $res2 = OrderProductModel::insert($data2);
            if (!$res2) {
                return error('订单商品添加失败');
            }
            $stock = $productinfo['stock'] - 1;
            // 商品表更新库存

            $ProductStatus = ProductModel::where('id', $proid)->update(['stock' => $stock]);


            //    $BusinessStatus = BusinessModel::where('id', 6)->update(['money' => 100]);
            if ($ProductStatus === false) {
                return error('操作失败');
            }

            DB::commit();
            return success('下单成功');
        } catch (\Exception $e) {
            DB::rollBack();

            // getMessage
            // var_dump($e);
            // exit;
            return error('订单创建失败');
        }
    }
    //查询订单
    public function sglindex()
    {
        $busid = request('busid', 0);
        $proid = request('proid', 0);
        $res = ProductModel::find($proid);
        if (!$res) {
            return error('商品不存在');
        }
        $data = [
            'busid' => $busid,
            'proid' => $proid,
            'price' => $res->price,
            'num' => 1,
            'total' => $res->price,
            'stock' => $res->stock,
            'name' => $res->name,
            'thumb_text' => $res->thumb_text,
            'desc' => $res->stock,

        ];


        return success('', $data);
    }

    //支付
    public function pay()
    {
        $busid = request('busid', 0);
        $orderid = request('orderid', 0);
        // var_dump($busid,$orderid);  
        $businessinfo = BusinessModel::find($busid);
        if (!$businessinfo) {
            return error('用户不存在');
        }
        $orderinfo = OrderModel::find($orderid);
        if (!$orderinfo) {
            return error('订单不存在');
        }

        DB::beginTransaction();
        try {
            //订单表
            $res1 = OrderModel::where('id', $orderid)->update(['status' => '1']);
            if ($res1 === false) {
                return error('支付失败');
            }
            //订单商品表查询商品号
            $orderproductinfo = OrderProductModel::where('orderid', $orderid)->first();
            if (!$orderproductinfo) {
                return error('订单商品不存在');
            }
            $proid = $orderproductinfo['proid'];

            //更新库存
            $productinfo = ProductModel::find($proid);


            //用户余额更新
            $businessinfo = BusinessModel::find($busid);
            $res3 = BusinessModel::where('id', $busid)->update(['money' => $businessinfo['money'] - $productinfo['price']]);
            if ($res3 === false) {
                return error('余额更新失败');
            }
            //消费记录
            $data = [
                'total' => $productinfo['price'],
                'content' => '商城订单号：' . $orderinfo['code'] . '---消费的金额' . $productinfo['price'] . '元',
                'busid' => $busid,
                'state' => '2'
            ];
            $res4 = RecordModel::create($data);
            if ($res4 === false) {
                return error('消费记录创建失败');
            }
            DB::commit();
            return success('支付成功');
        } catch (\Exception $e) {
            DB::rollBack();

            // getMessage
            // var_dump($e->getMessage);
            // exit;
            return error('支付失败');
        }
    }
}
